﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for SummaryForm.xaml
    /// </summary>

    public partial class SDTVKVV : DocumentBase
    {
        #region====================Properties=======================
        Queue<DataSet> JobQueue;
        ApplicationBase ApplicationBase;
        bool IsSetUp = false;
        DataSet SetMap = null;
        bool success = true;
        bool IsRunning = false;
        string failreason = "";
        string root = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\");
        public OracleConnection OracleDB;
        public SqlConnection SqlServerDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        INTEXDBC INTEXDBC;
        bool isrun = true;
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public DataSet SetExt;
        string Today
        {
            get
            {
                return System.DateTime.Now.Year.ToString()
                    + m_Data.Right("00" + System.DateTime.Now.Month.ToString(), 2)
                    + m_Data.Right("00" + System.DateTime.Now.Day.ToString(), 2);
            }
        }
        BATCHVKVV m_wintex;
        public SETINTEXDB Set4ITX
        {
            get
            {
                return (SETINTEXDB)TryFindResource("Set4ITX");
            }
        }
        public SETINTEXDB SetVITX
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetVITX");
            }
        }
        MKCAUTOVKABData m_Data;
        string UserID = "";        
        #region=====KDSTAMM=======
        #endregion
        #region=====KDSTAMM=======
        CollectionViewSource vwKDSTAMM
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwKDSTAMM");
            }
        }
        DataRow dwKDSTAMM
        {
            get
            {
                if (vwKDSTAMM.View == null)
                    return null;
                if ((DataRowView)vwKDSTAMM.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwKDSTAMM.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====VAART=======
        CollectionViewSource vwVAART
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwVAART");
            }
        }
        DataRow dwVAART
        {
            get
            {
                if (vwVAART.View == null)
                    return null;
                if ((DataRowView)vwVAART.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwVAART.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====VAFARBEN=======
        CollectionViewSource vwVAFARBEN
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwVAFARBEN");
            }
        }
        DataRow dwVAFARBEN
        {
            get
            {
                if (vwVAFARBEN.View == null)
                    return null;
                if ((DataRowView)vwVAFARBEN.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwVAFARBEN.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====VKKOPF=======
        CollectionViewSource vwVKKOPF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwVKKOPF");
            }
        }
        DataRow dwVKKOPF
        {
            get
            {
                if (vwVKKOPF.View == null)
                    return null;
                if ((DataRowView)vwVKKOPF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwVKKOPF.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====VKPOS=======
        CollectionViewSource vwVKPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwVKPOS");
            }
        }
        DataRow dwVKPOS
        {
            get
            {
                if (vwVKPOS.View == null)
                    return null;
                if ((DataRowView)vwVKPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwVKPOS.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====nwVKKOPF=======
        CollectionViewSource nwVKKOPF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("nwVKKOPF");
            }
        }
        CollectionViewSource nvVKKOPF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("nvVKKOPF");
            }
        }
        DataRow dnwVKKOPF
        {
            get
            {
                if (nwVKKOPF.View == null)
                    return null;
                if ((DataRowView)nwVKKOPF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)nwVKKOPF.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====nwVVLIEF=======
        CollectionViewSource nwVVLIEF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("nwVVLIEF");
            }
        }
        DataRow dnwVVLIEF
        {
            get
            {
                if (nwVVLIEF.View == null)
                    return null;
                if ((DataRowView)nwVVLIEF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)nwVVLIEF.View.CurrentItem).Row;
            }
        }

        #endregion
        #region=====nvVVLIEF=======
        CollectionViewSource nvVVLIEF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("nvVVLIEF");
            }
        }
        DataRow dvwVVLIEF
        {
            get
            {
                if (nvVVLIEF.View == null)
                    return null;
                if ((DataRowView)nvVVLIEF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)nvVVLIEF.View.CurrentItem).Row;
            }
        }

        #endregion
        #region=====vwKUNDVER=======
        CollectionViewSource vwKUNDVER
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwKUNDVER");
            }
        }
        DataRow dwKUNDVER
        {
            get
            {
                if (vwKUNDVER.View == null)
                    return null;
                if ((DataRowView)vwKUNDVER.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwKUNDVER.View.CurrentItem).Row;
            }
        }

        #endregion
        public SDTVKVV()
        {
            InitializeComponent();
            this.Name = "SDTVKVV";
            this.Title = "自动剪板";
            JobQueue = new Queue<DataSet>();
        }
        #endregion
        BackgroundWorker bgWorker;
        #region ===================Events========================
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (!IsSetUp)
            {
                ApplicationBase.Quit();
            }
            base.OnClosing(e);
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!IsSetUp)
                {
                    ApplicationBase = new ApplicationBase();
                    ApplicationBase.Load();
                    dicParamater = ApplicationBase.dicParamater;
      
                }
                bgWorker = new BackgroundWorker();
                bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);

                bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted;
                EventDispatcher.Instance.OnMessage += new EventHandler<MessageEventArgs>(_LogExplorerDock.OnMessage);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;
        }

        void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            IsRunning = false;
        }
        void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        { 
            if (!IsRunning)
            {
                IsRunning = true;
            }            
            AutoRun();
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            try
            {
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    base.SetUp(dicParamater);
                    this.dicParamater = dicParamater;
                    OracleDB = (OracleConnection)dicParamater["OracleDB"];
                    proxy = (IntexReptServBLClient)dicParamater["proxy"];
                    m_Data = new MKCAUTOVKABData(OracleDB, proxy);
                    INTEXDBC = new INTEXDBC(OracleDB, proxy);
                    IsSetUp = true;
                    ApplicationBase = (ApplicationBase)dicParamater["ApplicationBase"];

                    #region============TESTINGDATA================
                    txtKOLL.Text = "     ";
                    txtWBLO.Text = "02";
                    txtWBLB.Text = "  ";
                    txtUserID.Text = (string)dicParamater["User"];
                    txtPassword.Password = (string)dicParamater["Pwd"];
                    #endregion
                    ResetSetInterface();
                    ReloadCon();
                    SetExt = new DataSet();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnLogIn_Click(object sender, RoutedEventArgs e)
        {
            string Mandant = txtMANDANT.Text.ToUpper();
            string userID = m_Data.Left(txtUserID.Text.ToUpper() + "        ", 8);
            System.Security.SecureString SPassword = txtPassword.SecurePassword;
            txtLogIn.Background = new SolidColorBrush(Colors.Yellow);
            DataSet setResult = m_Data.LogIn(Mandant, userID, SPassword);
            if (setResult.Tables.Count > 0)
            {
                DataRow dwUser = setResult.Tables[0].Rows[0];
                txtSPRACHKZ.Text = dwUser["HRSPRKZ"].ToString();
                UserID = userID;
                m_Data.UserID = userID;
                this.UserID = userID;

                m_Data.WorkingDate = DateTime.Now.Year.ToString() + m_Data.Right("00" + DateTime.Now.Month.ToString(), 2)
                    + m_Data.Right("00" + DateTime.Now.Day.ToString(), 2);
                m_Data.MANDANT = Mandant;
                m_Data.SPRACHKZ = txtSPRACHKZ.Text.Trim();
                this.txtLogIn.Text = DateTime.Now.ToLocalTime().ToString() + ": " + userID + "已登录";
                txtLogIn.Background = new SolidColorBrush(Colors.Green);

            }
        }  
        private void btnSaveWork_Click(object sender, RoutedEventArgs e)
        {
            foreach (DataRow rw in SetData.Tables["VKKOPF"].Rows)
            {
                rw["VKKAENDDAT"] = Today;
            }
            DataSet SetJob = new DataSet();
            SaveJob();
            LoadJob();
            SetJob.Merge(SetExt);
            JobQueue.Enqueue(SetJob);
            if (IsRunning)
            {
                return;
            }
            if (!IsRunning)
            {
                bgWorker.RunWorkerAsync();
                //AutoRun();               
            }
        }
        private void btnResetSetDispo_Click(object sender, RoutedEventArgs e)
        {
            ResetSetInterface();
        }
        private void btnReloadCon_Click(object sender, RoutedEventArgs e)
        {
            ReloadCon();
        }

        private void dlgVKPOS_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView; 
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void txtCADCOLOR_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
        private void btnLogInfor_Click(object sender, RoutedEventArgs e)
        {
            LoadJob();
        }
        private void btnAutoRun_Click(object sender, RoutedEventArgs e)
        {
            bgWorker.RunWorkerAsync(); 
        }
        private void txtCADART_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {


            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }


        private void cbVAART_SelecteionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView;
                    if (SetData.Tables.Contains("VAFARBEN"))
                    {
                        SetData.Tables["VAFARBEN"].Clear();
                    }
                    if (dwVAART == null)
                        return;
                    DataRow row = SetData.VAFARBEN.NewRow();
                    row["VAFMANDANT"] = dwVAART["VAAMANDANT"];
                    row["VAFKOLL"] = dwVAART["VAAKOLL"];
                    row["VAFART"] = dwVAART["VAAART"];
                    DataSet Result = INTEXDBC.QueryVAFARBEN(row, 1);
                    SetData.Merge(Result, false, MissingSchemaAction.Ignore);
                    vwVAFARBEN.View.MoveCurrentToFirst();
                    while (true)
                    {
                        vwVAFARBEN.View.MoveCurrentToNext();
                        if (vwVAFARBEN.View.IsCurrentAfterLast)
                            break;
                    }
                    var query = from DataRow rowx in SetData.Tables["VAFARBEN"].AsEnumerable()
                                where rowx["VAFFILLER"].ToString().Trim() !="0"
                                select rowx;
                    if (query.Count() > 0)
                    {
                        DataTable tb = query.CopyToDataTable();
                        tb.TableName = "VAFARBEN";
                        SetData.Tables["VAFARBEN"].Clear();
                        SetData.Merge(tb);
                        SetData.AcceptChanges();
                        vwVAFARBEN.View.MoveCurrentToFirst();
                    }
                    else
                    {
                        SetData.Tables["VAFARBEN"].Clear();
                        Tracer.Info("布卷信息查询","没有布了!");
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void listVAFARBEN_SelecteionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView; 
                    if (dwVKPOS != null)
                    {
                        dwVKPOS["VKPKOLL"] = dwVAFARBEN["VAFKOLL"];
                        dwVKPOS["VKPART"] = dwVAFARBEN["VAFART"];
                        dwVKPOS["VKPFARBE"] = dwVAFARBEN["VAFFARBE"];
                    }
                    if (dwVAFARBEN["VAFFILLER"].ToString().Trim() != "")
                        return;
                    if (SetData.Tables.Contains("WBBST"))
                    {
                        SetData.Tables["WBBST"].Clear();
                    }
                    DataRow row = SetData.WBBST.NewRow();
                    row["WBBMANDANT"] = dwVAFARBEN["VAFMANDANT"];
                    row["WBBWAKZ"] = dwVAART["VAAARTST"];
                    row["WBBDISPOART"] = dwVAFARBEN["VAFPART"];
                    row["WBBDISPOVAR"] = dwVAFARBEN["VAFPVAR"];
                    row["WBBFARBE"] = dwVAFARBEN["VAFFFARBE"];
                    row["WBBBESCHICH"] = dwVAFARBEN["VAFBESCHICH"];
                    row["WBBDESS"] = dwVAFARBEN["VAFDESS"];
                    row["WBBCOLORIT"] = dwVAFARBEN["VAFCOLORIT"];
                    row["WBBLO"] = txtWBLO.Text.ToString();
                    row["WBBLB"] = txtWBLB.Text.ToString();

                    DataSet Result = INTEXDBC.QueryWBBST(row, 2);
                    double total = 0;
                    foreach (DataRow rw in Result.Tables[0].Rows)
                    {
                        double leng = 0;
                        double tleng = 0;
                        string tlength = rw["WBBTSTKLG"].ToString();
                        string stklg = rw["WBBISTKLG"].ToString();
                        if (stklg.Trim() != "")
                        {
                            leng = System.Convert.ToDouble(stklg) * 0.001;
                        }
                        if (tlength.Trim() != "")
                        {
                            tleng = System.Convert.ToDouble(tlength) * 0.001;
                        }
                        total += leng - tleng;
                    }
                    if (total < 0)
                        total = 0;
                    dwVAFARBEN["VAFFILLER"] = total.ToString();
                    if (Result != null)
                    {
                        SetData.Merge(Result, false, MissingSchemaAction.Ignore);
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnGetVAART_Click(object sender, RoutedEventArgs e)
        {
            ReSetVAART();
        }
        private void cbKDKUNDNA_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    SetData.KUNDVER.Clear();
                    drv = e.AddedItems[0] as DataRowView;
                    DataRow dwKUNDVER = SetData.KUNDVER.NewRow();
                    dwKUNDVER["KDVMANDANT"] = dwKDSTAMM["KDMANDANT"].ToString();
                    dwKUNDVER["KDVKUNDNR"] = dwKDSTAMM["KDKUNDNR"].ToString();
                    DataSet Result = INTEXDBC.QueryKUNDVER(dwKUNDVER, 2);
                    SetData.Merge(Result, false, MissingSchemaAction.Ignore);
                    SetData.KUNDVER.AcceptChanges();
                    if (vwKUNDVER != null)
                    {
                        vwKUNDVER.View.MoveCurrentToFirst();
                    } 
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        #endregion
        private void btnAddNewOrder_Click(object sender, RoutedEventArgs e)
        {
            if (cbKDKUNDNA.Text.Trim() == "")
                return;
            if (SetData.Tables.Contains("VKKOPF"))
            {
                SetData.Tables["VKKOPF"].Clear();
            }
            SetData.Tables["VKPOS"].Clear();
            Set4ITX.Clear();
            DataRow row = SetData.Tables["VKKOPF"].NewRow();
            row["VKKMANDANT"] = "00";
            row["VKKAUFKRS"] = txtVKKAUFKRS.Text.ToString();
            row["VKKAUFLFD"] = "*";
            row["VKKNEUBEN"] = "ITXMVKVV";
            row["VKKNEUDAT"] = Today;
            row["VKKAENDZL"] = 0;
            row["VKKVB"] = m_Data.Left(cbKUNDVER.Text.ToString().Trim() + "   ", 3);
            if (dwKDSTAMM != null)
            {
                row["VKKKUNDNR"] = dwKDSTAMM["KDKUNDNR"].ToString();
                /*下面这个字段是修改订单行的用户名为什么记录为客户简称呢？*/
                row["VKKAENDBEN"] = m_Data.Left(dwKDSTAMM["KDKUNDNA"].ToString(), 8);
            }
            else
            {
                row["VKKKUNDNR"] = "";
                //row["KUNDNAME"] = cbKDKUNDNA.Text.ToString();
            }
            SetData.Tables["VKKOPF"].Rows.Add(row);
            if (SetData.Tables.Contains("VKPOS"))
            {
                SetData.Tables["VKPOS"].Clear();
            }
            vwVKKOPF.View.MoveCurrentToFirst();
            btnAddNewOrderLine_Click(null, null);

        }
        private void btnAddNewOrderLine_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DataRow row = SetData.VKPOS.NewRow();
                if (dwVKPOS != null)
                {
                    row.ItemArray = dwVKPOS.ItemArray;
                }
                else
                {
                    row["VKPMANDANT"] = dwVKKOPF["VKKMANDANT"].ToString();
                    row["VKPAUFKRS"] = dwVKKOPF["VKKAUFKRS"].ToString();
                    row["VKPAUFLFD"] = dwVKKOPF["VKKAUFLFD"].ToString();
                    row["VKPLIEFTERM"] = Today;
                    row["VKPMEEH"] = txtMEEH.Text.ToString();
                    row["VKPMENGE1"] = 100;
                    row["VKPPREIS"] = 0;
                }
                string pos = dwVKKOPF["VKKAENDZL"].ToString();
                row["VKPAUFPOS"] = System.Convert.ToInt16(pos) + 1;
                dwVKKOPF["VKKAENDZL"] = row["VKPAUFPOS"].ToString();
                SetData.Tables["VKPOS"].Rows.Add(row);
                vwVKPOS.View.MoveCurrentToLast();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void Convert2Intex(ref bool success, ref string failreason, ref DataSet jobdata)
        {
            DataSet setResult = new DataSet();
            try
            {
                if (jobdata.Tables["VKKOPF_EXT"].Rows.Count == 0)
                    return;
                m_Data.SetExt = jobdata;
                m_Data.SetExt.Merge(SetMap);
                //m_Data.SetExt.Merge(SetData);
                setResult = m_Data.ConvertToIntex(ref success, ref failreason);
                if (!success)
                {
                    return;
                }
                jobdata.Clear();
                jobdata.Merge(setResult);
                if (m_wintex == null)
                {
                    m_wintex = new WPFExcelReport.BATCHVKVV(OracleDB, proxy);
                }
                //m_wintex.ReSet(Set4ITX, null);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public bool Upload2Intex(ref DataSet jobdata)
        {
            bool result = true;
            try
            {
                if (m_wintex == null)
                {
                    m_wintex = new BATCHVKVV(OracleDB, proxy);
                }
                m_wintex.ReSet(jobdata, null);
                result = m_wintex.Execute(null);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return result;
        }
        public void Delete2Intex()
        {
            if (m_wintex == null)
            {
                m_wintex = new BATCHVKVV(OracleDB, proxy);
            }
            m_wintex.ReSet(Set4ITX, null);
            m_wintex.Delete();
        }
        public void ReSetVAART()
        {
            SetData.Tables["VAART"].Clear();
            DataSet setResult = new DataSet();
            DataRow row = SetData.VAART.NewRow();
            row["VAAMANDANT"] = txtMANDANT.Text.ToString();
            row["VAAKOLL"] = txtKOLL.Text.ToString();
            row["VAAART"] = "";
            setResult = INTEXDBC.QueryVAART(row, 1);
            SetData.Merge(setResult);
        }
        public void ReSetKDSTAMM()
        {
            SetData.Tables["KDSTAMM"].Clear();
            DataSet setResult = new DataSet();
            DataRow row = SetData.KDSTAMM.NewRow();
            row["KDMANDANT"] = txtMANDANT.Text.ToString();
            setResult = INTEXDBC.QueryKDSTAMM(row, 1);
            SetData.Merge(setResult);
        }
        public void ReloadCon()
        {
            ReSetVAART();
            ReSetKDSTAMM();
        }
        public void ResetSetInterface()
        {
            SetMap = new SETINTEXDB();
            DataSet setResult = new DataSet();
            string filePath = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\VKVVMAPINTEX.XML");
            setResult.ReadXml(filePath);
            SetMap.Merge(setResult);
            SetMap.Tables["VKKOPF_EXT"].Clear();
            SetMap.Tables["VKPOS_EXT"].Clear(); 
        }

        public void LoadJob()
        {
            try
            {
                SetExt = new DataSet();
                DataSet setResult = m_Data.GetJob();
                SetExt.Merge(setResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void SaveJob()
        {
            if (SetData.VKPOS.Rows.Count == 0)
                return;
            if (SetData.VKKOPF.Rows[0]["VKKAENDDAT"].ToString().Trim() == "")
                return;
            DataSet SetOrder = new DataSet();
            SetOrder.Merge(SetMap.Tables["VKKOPF_EXT"]);
            SetOrder.Merge(SetMap.Tables["VKPOS_EXT"]);
            foreach (DataRow row in SetData.VKKOPF.Rows)
            {
                DataRow rVK = SetOrder.Tables["VKKOPF_EXT"].NewRow();
                rVK["VKKMANDANT"] = row["VKKMANDANT"].ToString();
                rVK["VKKAUFKRS"] = row["VKKAUFKRS"].ToString();
                rVK["VKKAUFLFD"] = row["VKKAUFLFD"].ToString();
                rVK["VKKNEUBEN"] = row["VKKNEUBEN"].ToString();
                rVK["VKKNEUDAT"] = row["VKKNEUDAT"].ToString();
                rVK["VKKKUNDNR"] = row["VKKKUNDNR"].ToString();
                rVK["KUNDNAME"] = row["VKKAENDBEN"].ToString();
                rVK["VKKVB"] = row["VKKVB"].ToString();
                rVK["VKKAENDDAT"] = row["VKKAENDDAT"].ToString();
                SetOrder.Tables["VKKOPF_EXT"].Rows.Add(rVK);
            }
            foreach (DataRow row in SetData.VKPOS.Rows)
            {
                DataRow rVK = SetOrder.Tables["VKPOS_EXT"].NewRow();
                rVK["VKPMANDANT"] = row["VKPMANDANT"].ToString();
                rVK["VKPAUFKRS"] = row["VKPAUFKRS"].ToString();
                rVK["VKPAUFLFD"] = row["VKPAUFLFD"].ToString();
                rVK["VKPAUFPOS"] = row["VKPAUFPOS"].ToString();
                rVK["VKPARTST"] = row["VKPARTST"].ToString();
                rVK["VKPKOLL"] = row["VKPKOLL"].ToString();
                rVK["VKPART"] = row["VKPART"].ToString();
                rVK["VKPFARBE"] = row["VKPFARBE"].ToString();
                rVK["VKPMENGE1"] = row["VKPMENGE1"].ToString();
                rVK["VKPMEEH"] = row["VKPMEEH"].ToString();
                rVK["VKPLIEFTERM"] = row["VKPLIEFTERM"].ToString();
                rVK["VKPPREIS"] = row["VKPPREIS"].ToString();
                rVK["VKPPREH"] = row["VKPPREH"].ToString();
                rVK["VKPNEUBEN"] = row["VKPNEUBEN"].ToString();
                rVK["VKPNEUDAT"] = row["VKPNEUDAT"].ToString();
                double VKPPREIS = System.Convert.ToDouble(rVK["VKPPREIS"].ToString()) * 0.001;
                double VKPMENGE1 = System.Convert.ToDouble(rVK["VKPMENGE1"].ToString()) * 0.01;
                double VKPPOSWERT = System.Math.Round(VKPPREIS * VKPMENGE1, 0);
                rVK["VKPPOSWERT"] = VKPPOSWERT;
                SetOrder.Tables["VKPOS_EXT"].Rows.Add(rVK);
            }
            m_Data.SaveJob(SetOrder);
            SetData.VKKOPF.Clear();
            SetData.VKPOS.Clear();
        }
        public void AutoRun()
        {
           
            try
            {
                DataSet SetJob = new DataSet();
                if (isrun == false)
                    return;
                while (JobQueue.Count > 0)
                {
                    SetJob = JobQueue.Dequeue();
                                        
                    if (SetJob.Tables.Contains("VKKOPF_EXT"))
                    {
                        if (SetJob.Tables["VKKOPF_EXT"].Rows.Count > 0)
                        {                            
                            AutoConvert(SetJob);                           
                        }
                    }
                }               
            }
            catch (Exception ex)
            {
                IsRunning = false;
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                this.Dispatcher.Invoke(new Action(()=>{
                    if (nvVVLIEF.View != null)
                    {
                        nvVVLIEF.View.MoveCurrentToFirst();
                    }
                    if (nvVKKOPF.View != null)
                    {
                        nvVKKOPF.View.MoveCurrentToFirst(); 
                    }
                }));                   
            }
        }
        /// <summary>
        /// Load external data. usually this is used to load detail informations with a code.
        /// </summary>
        /// <param name="fInterID"></param>
        /// <param name="fClothNO"></param>
        /// <param name="fColorNo"></param>

        public DataSet ReadFile(string filePath)
        {
            DataSet setResult = new DataSet();
            try
            {
                if (System.IO.File.Exists(filePath))
                {
                    setResult.ReadXml(filePath);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setResult;
        }

        public void AutoConvert(DataSet jobdata)
        {
            //<VKKAUFKRS> VKKAUFLFD> VKKNEUBEN>
            try
            {
                DataSet setResult = new DataSet();
                bool result = true;

                success = true;
                failreason = "";
                EventDispatcher.Instance.RaiseStatus("开始转换:", StatusEventType.RunningProgress);
                Convert2Intex(ref success, ref failreason, ref jobdata);
                SetVITX.Merge(jobdata);
                this.Dispatcher.Invoke(new Action(() =>
                {
                    listVKFLFD.Text = "";
                    foreach (DataRow dw in SetVITX.Tables["VKKOPF"].Rows)
                    {
                        listVKFLFD.Text += dw["VKKAUFLFD"].ToString() + ";" + Environment.NewLine;
                    }
                    listVVFLFD.Text = "";
                    foreach (DataRow dw in SetVITX.Tables["VVLIEF"].Rows)
                    {
                        listVVFLFD.Text += dw["VVLIEFSCH"].ToString() + ";" + Environment.NewLine;
                    }
                }));   
                if (!success)
                {
                    result = false;
                }
                else
                {
                    result = Upload2Intex(ref jobdata);
                    EventDispatcher.Instance.RaiseStatus("保存到Intex:", StatusEventType.StopProgress);
                }
                DataRow dwInput = jobdata.Tables["VKKOPF"].Rows[0];
                WritePFLog(result, failreason, dwInput);
            }
            catch(Exception  ex)
            {}
            finally
            {
          
            }
        }
        public void WritePFLog(bool pass, string reason, DataRow dwLog)
        {
            return;
            DataTable tbLog = Set4ITX.Tables["VKKOPF"].Clone();
            DataSet setResult = new DataSet();
            DataSet setL = new DataSet();
            string logfile = "ITXLOG";
            if (!pass)
            {
                logfile = "FAILLOG";
                tbLog.TableName = logfile;
            }
            else
            {
                logfile = "PASSLOG";
                tbLog.TableName = logfile;
            }
            if (System.IO.File.Exists(root + logfile + ".XML"))
            {
                setResult.ReadXml(root + logfile + ".XML");
                tbLog = setResult.Tables[logfile];
            }
            tbLog.Rows.Add(tbLog.NewRow().ItemArray = dwLog.ItemArray);
            setL.Merge(tbLog);
            setL.WriteXml(root + logfile + ".XML");
            //Last ID                 
            setL = new DataSet();
            tbLog = Set4ITX.Tables["VKKOPF"].Clone();
            logfile = "CADLOG";
            tbLog.TableName = logfile;
            tbLog.Rows.Add(tbLog.NewRow().ItemArray = dwLog.ItemArray);
            setL.Merge(tbLog);
            setL.WriteXml(root + logfile + ".XML");
        }

        private void btnStopRun_Click(object sender, RoutedEventArgs e)
        {
            IsRun.Text = "N";
            btnAutoRun.Content = "自动";
        }

        private void IsRun_TextChanged(object sender, TextChangedEventArgs e)
        {
            isrun = false;
            if (IsRun.Text.ToString() == "Y")
                isrun = true;
        }

        private void butExcelLoad_Click(object sender, RoutedEventArgs e)
        {
            DataSet Result=m_Data.LoadExcelVKVV();
            if (SetData.Tables.Contains("VKKOPF_EXT"))
            {
                SetData.Tables["VKKOPF_EXT"].Clear();
            }
            if (SetData.Tables.Contains("VKPOS_EXT"))
            {

                SetData.Tables["VKPOS_EXT"].Clear();
            }
            SetData.Merge(Result);
            SetData.AcceptChanges();
        }
    }
}